package data.user;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Andrea
 */
class UserDB implements AutoCloseable {

    private static final UserDB INSTANCE;
    private static Connection connection;

    static {
        INSTANCE = new UserDB();
    }

    @SuppressWarnings("ResultOfObjectAllocationIgnored")
    private UserDB() {
        try {
            String url = "jdbc:mysql://localhost:3306/";
            String dbName = "parallelcomputing";
            String userName = "usersManager";
            String password = "usersManager";
            new com.mysql.jdbc.Driver();

            connection = DriverManager.getConnection(url + dbName, userName, password);

        } catch (SQLException ex) {
            Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    static boolean signup(User u) {
        try {
            //creating user access to database, mustr grant to him his access to some tables
            PreparedStatement st1 = connection.prepareCall(
                    "create user \"" + u.getId() + "\"@\"%\" identified by \"" + u.getPassword() + "\""
            );
            //adding him to clients table
            PreparedStatement st2 = connection.prepareStatement(
                    "insert into clients (id, password) values(" + u.getId() + ", \"" + u.getPassword() + "\")"
            );

            st1.executeUpdate();
            st2.executeUpdate();

            return true;
        } catch (SQLException ex) {
            Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, null, ex);

            return false;
        }
    }
    
    static boolean autenthicate(User u){
        try {
            PreparedStatement st1 = connection.prepareStatement(
                    "select * from clients where id = " + u.getId() + " AND password = " + u.getPassword()
            );
            
            ResultSet rs = st1.executeQuery();
            
            
        } catch (SQLException ex) {
            Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return true;
    }
    
    @Override
    public void close() throws SQLException {
        connection.close();
    }

    static private void debugUserTable() {
        try {
            PreparedStatement st1 = connection.prepareStatement(
                    "select * from clients"
            );
            
            ResultSet rs = st1.executeQuery();
            
            while (rs.next()) {
                System.out.println(rs.getInt("id"));
            }
        } catch (SQLException ex) {
            Logger.getLogger(UserDB.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
